<template>
  <div>
    <el-form
      ref="form"
      :rules="rules"
      style="padding-top: 10px"
      :model="form"
      label-width="120px"
    >
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="劳务合同编号" prop="contractNumber">
            <el-input
              v-model="form.contractNumber"
              readonly
              :disabled="disableForm || optType !== 'add'"
              @click.native="
                optType === 'add' ? (showTransferListModal = true) : null
              "
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-circle-plus-outline"
              />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="劳务合同名称" prop="contractName">
            <el-input v-model="form.contractName" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="劳务合同结算编号" prop="settleNumber">
            <el-input v-model="form.settleNumber" placeholder="自动生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分包队伍编号" prop="teamNumber">
            <el-input v-model="form.teamNumber" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分包队伍名称" prop="teamName">
            <el-input v-model="form.teamName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同额" prop="contractAmount">
            <el-input v-model="form.contractAmount" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算期次(年+月)" prop="period">
            <!-- <el-input v-model="form.period" :disabled="disableForm" /> -->
            <el-date-picker
              v-model="form.period"
              :disabled="disableForm"
              type="month"
              value-format="yyyy-MM"
              style="width: 200px"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本次结算金额" prop="thisSettleAmount">
            <el-input v-model="form.thisSettleAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开累结算金额" prop="accruedSettleAmount">
            <el-input
              v-model="form.accruedSettleAmount"
              :disabled="disableForm"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" :disabled="disableForm" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="btns" style="padding-bottom: 10px">
        <el-button type="primary" :disabled="disableForm" @click="addRow">新增行</el-button>
        <el-button type="primary" :disabled="disableForm" @click="delDetailDataItem">删除行</el-button>
      </div>
      <com-table
        v-model="selectRow"
        :no-page="true"
        :columns="columns"
        highlight-current-row
        :data="detailDataList"
      >
        <template v-slot:conNumber="{ row }">
          <el-input v-model="row.conNumber" :disabled="disableForm" />
        </template>
        <template v-slot:conName="{ row }">
          <el-input v-model="row.conName" :disabled="disableForm" />
        </template>
        <template v-slot:conUnit="{ row }">
          <el-input v-model="row.conUnit" :disabled="disableForm" />
        </template>
        <template v-slot:conUnitPrice="{ row }">
          <el-input v-model="row.conUnitPrice" :disabled="disableForm" @input="getConSumPrice" />
        </template>
        <template v-slot:conCount="{ row }">
          <el-input v-model="row.conCount" :disabled="disableForm" @input="getConSumPrice" />
        </template>
        <template v-slot:conSumPrice="{ row }">
          <el-input v-model="row.conSumPrice" :disabled="disableForm" />
        </template>
        <template v-slot:tsCount="{ row }">
          <el-input v-model="row.tsCount" :disabled="disableForm" @input="getTsAmount" />
        </template>
        <template v-slot:tsAmount="{ row }">
          <el-input v-model="row.tsAmount" disabled />
        </template>
        <template v-slot:asCount="{ row }">
          <el-input v-model="row.asCount" :disabled="disableForm" @input="getAsAmount" />
        </template>
        <template v-slot:asAmount="{ row }">
          <el-input v-model="row.asAmount" disabled />
        </template>
        <template v-slot:ctsCount="{ row }">
          <el-input v-model="row.ctsCount" :disabled="disableForm" @input="getCtsAmount" />
        </template>
        <template v-slot:ctsAmount="{ row }">
          <el-input v-model="row.ctsAmount" disabled />
        </template>
        <template v-slot:cpAmount="{ row }">
          <el-input v-model="row.cpAmount" :disabled="disableForm" @input="getCasAmount" />
        </template>
        <template v-slot:tpAmount="{ row }">
          <el-input v-model="row.tpAmount" :disabled="disableForm" />
        </template>
        <template v-slot:remark="{ row }">
          <el-input v-model="row.remark" :disabled="disableForm" />
        </template>
      </com-table>
      <el-button
        style="margin-top: 10px"
        type="primary"
        @click="showFileModal = true"
      >附件资料({{ fileList.length }})</el-button>
      <file-uploader
        v-model="fileList"
        :show-modal.sync="showFileModal"
        :disabled="disableForm"
        :can-download="optType === 'detail'"
      />
    </el-form>
  </div>
</template>

<script>
import {
  addTransferContractSettleInfo,
  updateTransferContractSettleInfo,
  getTransferContractSettleInfoDetail,
  getLaborContractChecklistList,
  getLaborContractSettleChecklistCountInfo
} from '@/api/runManage'
import { getAreaList } from '@/api/common'
import { workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
export default {
  name: 'AddTransferContractSettleInfo',
  components: {
    fileUploader
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showFileModal: false,
      targetList: [],
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        settleNumber: '',
        teamNumber: '',
        teamName: '',
        contractNumber: '',
        contractName: '',
        contractAmount: '',
        period: '',
        thisSettleAmount: '',
        accruedSettleAmount: '',
        projectName: '',
        addWorkflowId: '',
        status: '',
        remark: '',
        founderName: '',
        founderUnit: '',
        createTime: ''
      },
      showAddDetailModal: false,
      selectRow: null,
      detailDataList: [],
      detailDataItem: {},
      columns: [
        {
          label: '编号',
          slot: 'conNumber'
        },
        {
          label: '名称',
          slot: 'conName',
          width: '150'
        },
        {
          label: '单位',
          slot: 'conUnit'
        },
        {
          label: '单价(元)',
          slot: 'conUnitPrice',
          width: '150'
        },
        {
          label: '数量',
          slot: 'conCount',
          width: '150'
        },
        {
          label: '合价(元)',
          slot: 'conSumPrice',
          width: '150'
        },
        {
          label: '本次结算-结算数量',
          slot: 'tsCount',
          width: '130'
        },
        {
          label: '本次结算-结算金额',
          slot: 'tsAmount',
          width: '130'
        },
        {
          label: '开累结算-结算数量',
          slot: 'asCount',
          width: '130'
        },
        {
          label: '开累结算-结算金额',
          slot: 'asAmount',
          width: '130'
        },
        // {
        //   label: "按合同约定本期结算-结算数量",
        //   slot: "ctsCount",
        //   width: '190'
        // },
        // {
        //   label: "按合同约定本期结算-结算金额",
        //   slot: "ctsAmount",
        //   width: '190'
        // },
        {
          label: '累计实付金额',
          slot: 'cpAmount',
          width: '100'
        },
        {
          label: '本期支付金额',
          slot: 'tpAmount',
          width: '100'
        },
        {
          label: '备注',
          slot: 'remark'
        }
      ],
      showTargetSetListModal: false,
      showTransferListModal: false,
      fileList: [],
      rules: {
        name: [{ required: true, message: '单位名称', trigger: 'change' }],
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码', trigger: 'change' }
        ]
      },
      detailRules: {
        conNumber: [
          { required: true, message: '请输入合同-清单编号', trigger: 'change' }
        ],
        conName: [
          { required: true, message: '请输入合同清单名称', trigger: 'change' }
        ],
        conUnit: [
          { required: true, message: '请输入合同-单位', trigger: 'change' }
        ],
        conUnitPrice: [
          { required: true, message: '请输入合同-单价(元)', trigger: 'change' }
        ],
        conSumPrice: [
          { required: true, message: '请输入合同-合价(元)', trigger: 'change' }
        ],
        conCount: [
          { required: true, message: '请输入合同-数量', trigger: 'change' }
        ],
        tsCount: [
          {
            required: true,
            message: '请输入本次结算-结算数量',
            trigger: 'change'
          }
        ],
        tsAmount: [
          {
            required: true,
            message: '请输入本次结算-结算金额',
            trigger: 'change'
          }
        ],
        asCount: [
          {
            required: true,
            message: '请输入开累结算-结算数量',
            trigger: 'change'
          }
        ],
        asAmount: [
          {
            required: true,
            message: '请输入开累结算-结算金额',
            trigger: 'change'
          }
        ],
        ctsCount: [
          {
            required: true,
            message: '请输入按合同本次结算-结算数量',
            trigger: 'change'
          }
        ],
        ctsAmount: [
          {
            required: true,
            message: '请输入按合同本次结算-结算金额',
            trigger: 'change'
          }
        ],
        casCount: [
          {
            required: true,
            message: '请输入按合同开累结算-结算数量',
            trigger: 'change'
          }
        ],
        casAmount: [
          {
            required: true,
            message: '请输入按合同开累结算-结算金额',
            trigger: 'change'
          }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    data: {
      handler(newData, oldData) {
        if (newData.businessId) {
          this.getDocDetail(newData.businessId)
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    // 获取劳务分包合同结算清单数量信息
    getLaborContractSettleChecklistCountInfo(laborContractNumber, laborContractSettleChecklistNumber, row) {
      const params = {
        laborContractNumber: laborContractNumber,
        laborContractSettleChecklistNumber: laborContractSettleChecklistNumber
      }
      getLaborContractSettleChecklistCountInfo(params).then((res) => {
        if (res.code === '0001') {
          row.asCount = res.data || 0
          this.getAsAmount()
          this.getCasAmount()
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 获取按合同开累结算-结算金额
    getCasAmount() {
      let casCount = 0
      let conUnitPrice = 0
      if (this.selectRow.casCount) {
        casCount = this.selectRow.casCount
      }
      if (this.selectRow.conUnitPrice) {
        conUnitPrice = this.selectRow.conUnitPrice
      }
      const casAmount = Number.parseFloat(casCount) * Number.parseFloat(conUnitPrice)
      this.selectRow.casAmount = casAmount.toFixed(2)
    },
    // 获取本次结算结算金额
    getTsAmount() {
      let sum = 0
      this.detailDataList.forEach(item => {
        let tsCount = 0
        let conUnitPrice = 0
        if (this.selectRow.tsCount) {
          tsCount = this.selectRow.tsCount
        }
        if (this.selectRow.conUnitPrice) {
          conUnitPrice = this.selectRow.conUnitPrice
        }
        const tsAmount = Number.parseFloat(tsCount) * Number.parseFloat(conUnitPrice)
        sum += tsAmount
        this.selectRow.tsAmount = tsAmount.toFixed(2)
      })
      this.form.thisSettleAmount = sum.toFixed(2)
    },
    // 获取开累结算-结算金额
    getAsAmount() {
      let sum = 0
      this.detailDataList.forEach(item => {
        let asCount = 0
        let conUnitPrice = 0
        if (this.selectRow.asCount) {
          asCount = this.selectRow.asCount
        }
        if (this.selectRow.conUnitPrice) {
          conUnitPrice = this.selectRow.conUnitPrice
        }
        const asAmount = Number.parseFloat(asCount) * Number.parseFloat(conUnitPrice)
        sum += asAmount
        this.selectRow.asAmount = asAmount.toFixed(2)
      })
      this.form.accruedSettleAmount = sum.toFixed(2)
    },
    // 获取按合同本次结算-结算金额
    getCtsAmount() {
      let ctsCount = 0
      let conUnitPrice = 0
      if (this.selectRow.ctsCount) {
        ctsCount = this.selectRow.ctsCount
      }
      if (this.selectRow.conUnitPrice) {
        conUnitPrice = this.selectRow.conUnitPrice
      }
      const ctsAmount = Number.parseFloat(ctsCount) * Number.parseFloat(conUnitPrice)
      this.selectRow.ctsAmount = ctsAmount.toFixed(2)
    },
    getConSumPrice() {
      let conUnitPrice = 0
      let conCount = 0
      if (this.selectRow.conUnitPrice) {
        conUnitPrice = this.selectRow.conUnitPrice
      }
      if (this.selectRow.conCount) {
        conCount = this.selectRow.conCount
      }
      const conSumPrice = Number.parseFloat(conUnitPrice) * Number.parseFloat(conCount)
      this.selectRow.conSumPrice = conSumPrice.toFixed(2)
      // 获取本次结算-结算金额
      this.getTsAmount()
      // 获取开累结算-结算金额
      this.getAsAmount()
      // 获取按合同本次结算-结算金额
      this.getCtsAmount()
      // 获取按合同开累结算-结算金额
      this.getCasAmount()
    },
    addRow() {
      this.detailDataList = [
        ...this.detailDataList,
        {
          conNumber: '',
          conName: '',
          conUnit: '',
          conUnitPrice: '',
          conCount: '',
          conSumPrice: '',
          tsCount: '',
          tsAmount: '',
          asCount: '',
          asAmount: '',
          ctsCount: '',
          ctsAmount: '',
          casCount: '',
          casAmount: '',
          remark: ''
        }
      ]
    },
    sum() {
      this.detailDataItem.tsAmount =
        this.detailDataItem.conUnitPrice * 1 * this.detailDataItem.tsCount * 1
      if (isNaN(this.detailDataItem.tsAmount)) {
        this.detailDataItem.tsAmount = ''
      }
      this.detailDataItem.asCount = this.detailDataItem.tsAmount
      this.detailDataItem.asAmount = this.detailDataItem.tsAmount

      this.$forceUpdate()
    },
    getSelectedRowsTransfer(obj) {
      this.form.contractNumber = obj.contractNumber
      // this.form.settleNumber = obj.contractNumber
      this.form.teamName = obj.teamName
      this.form.contractName = obj.contractName
      this.form.teamNumber = obj.teamNumber
      this.form.projectName = obj.projectName
      this.form.contractAmount = obj.initAmount
      getLaborContractChecklistList({
        laborContractInfoId: obj.id
      }).then((res) => {
        const list = []
        res.data.forEach((item) => {
          const element = {
            ...this.optType === 'add' ? {} : {
              id: item.id
            },
            conNumber: item.number,
            conName: item.name,
            conUnit: item.unit,
            conUnitPrice: item.unitPrice,
            conCount: item.count,
            conSumPrice: item.sumPrice,
            asCount: 0
          }
          // 获取劳务合同结算清单数量
          this.getLaborContractSettleChecklistCountInfo(obj.contractNumber, item.number, element)
          list.push(element)
        })
        this.detailDataList = list
      })
    },
    addDetail() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          const item = JSON.parse(JSON.stringify(this.detailDataItem))
          this.detailDataList.push(item)
          this.showAddDetailModal = false
          this.$refs.detailForm.resetFields()
        }
      })
    },
    cancelAddDetail() {
      this.showAddDetailModal = false
    },
    delDetailDataItem() {
      if (this.selectRow) {
        const index = this.detailDataList.indexOf(this.selectRow)
        this.detailDataList.splice(index, 1)
      }
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter((val) => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then((res) => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getTransferContractSettleInfoDetail({
        laborContractSettleInfoId: id
      }).then((res) => {
        const { lstAttachment, laborContractSettleInfo, lstLaborContractSettleChecklist } = res.data || {}
        Object.keys(this.form).forEach(key => {
          const source = laborContractSettleInfo[key]
          if (typeof source === 'boolean') {
            this.form[key] = source ? 1 : 0
          } else {
            this.form[key] = source
          }
        })
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (
          lstLaborContractSettleChecklist &&
          lstLaborContractSettleChecklist.length > 0
        ) {
          this.detailDataList = lstLaborContractSettleChecklist
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then((res) => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {},
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            laborContractSettleInfo: {
              ...this.form,
              ...(this.optType === 'edit'
                ? {
                  id: this.data.id
                }
                : {})
            },
            lstLaborContractSettleChecklist: this.detailDataList.map((item) => {
              return {
                ...item,
                ...(this.optType === 'edit'
                  ? {
                    laborContractSettleInfoId: this.data.id
                  }
                  : {})
              }
            }),
            lstAttachment: this.fileList
          }
          const fn =
            this.optType === 'add'
              ? addTransferContractSettleInfo
              : updateTransferContractSettleInfo
          fn(params).then((res) => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    inputConUnitPrice() {
      let sum = 0
      let sum2 = 0
      let sum3 = 0
      let sum4 = 0
      this.detailDataList.forEach((item, index) => {
        if (item.conUnitPrice && item.tsCount) {
          item.tsAmount = Number.parseFloat(item.conUnitPrice) * Number.parseFloat(item.tsCount)
          item.tsAmount = Number.parseFloat(item.tsAmount).toFixed(2)
          sum3 = sum3 + Number.parseFloat(item.tsAmount)
          // 开累数量
          sum = sum + Number.parseFloat(item.tsCount)
          item.asCount = Number.parseFloat(sum).toFixed(2)
          // 开累金额
          sum2 = sum2 + Number.parseFloat(item.tsAmount)
          item.asAmount = Number.parseFloat(sum2).toFixed(2)
          sum4 = sum4 + Number.parseFloat(item.asAmount)
        } else {
          item.tsAmount = ''
          this.detailDataItem.tsAmount = ''
        }
        this.form.thisSettleAmount = Number.parseFloat(sum3).toFixed(2)
        this.form.accruedSettleAmount = Number.parseFloat(sum4).toFixed(2)
        this.$forceUpdate()
      })
    },
    inputTsCount() {
      let sum = 0
      let sum2 = 0
      let sum3 = 0
      let sum4 = 0
      this.detailDataList.forEach((item, index) => {
        if (item.conUnitPrice && item.tsCount) {
          item.tsAmount = Number.parseFloat(item.conUnitPrice) * Number.parseFloat(item.tsCount)
          item.tsAmount = Number.parseFloat(item.tsAmount).toFixed(2)
          sum3 = sum3 + Number.parseFloat(item.tsAmount)
          // 开累数量
          sum = sum + Number.parseFloat(item.tsCount)
          item.asCount = Number.parseFloat(sum).toFixed(2)
          // 开累金额
          sum2 = sum2 + Number.parseFloat(item.tsAmount)
          item.asAmount = Number.parseFloat(sum2).toFixed(2)
          sum4 = sum4 + Number.parseFloat(item.asAmount)
        } else {
          item.tsAmount = ''
          this.detailDataItem.tsAmount = ''
        }
        this.form.thisSettleAmount = Number.parseFloat(sum3).toFixed(2)
        this.form.accruedSettleAmount = Number.parseFloat(sum4).toFixed(2)
        this.$forceUpdate()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
::v-deep .el-form-item__label{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;

}
</style>
